package com.osmino.contacts.search;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.os.AsyncTask;
import com.osmino.contacts.entity.Contact;

abstract class AsyncDublicatesSearcher extends AsyncTask<Void, Void, Void> {
	
	protected final ISearchDublicateController mController;
	protected final List<Contact> mContacts;
	protected Map<String, List<Contact>> mMapPossibleDublicates;

	public AsyncDublicatesSearcher(ISearchDublicateController controller, List<Contact> contacts) {
		mController = controller;
		mContacts = contacts;
	}

	@Override
	protected void onPreExecute() {
		mMapPossibleDublicates = new HashMap<String, List<Contact>>();
	}
	
	@Override
	protected Void doInBackground(Void... params) {
		List<String> constraintList = new ArrayList<String>();
		for (Contact contact : mContacts) {
			fillConstraintList(contact, constraintList);
			for (String constraint : constraintList) {
				List<Contact> contactsList = mMapPossibleDublicates.get(constraint);
				if (contactsList == null) {
					contactsList = new ArrayList<Contact>();
					mMapPossibleDublicates.put(constraint, contactsList);
				}
				contactsList.add(contact);
			}
			constraintList.clear();
		}
		return null;
	}
	
	protected abstract void fillConstraintList(Contact contact, List<String> constraintList);
	
	@Override
	protected void onPostExecute(Void result) {
		List<SearchStructure> resultList = new ArrayList<SearchStructure>();
		for (String constraint : mMapPossibleDublicates.keySet()) {
			List<Contact> contacts = mMapPossibleDublicates.get(constraint);
			if (contacts.size() > 1) {
				SearchStructure structure = new SearchStructure(constraint, contacts);
				resultList.add(structure);
			}
		}
		mController.onDublicatesFound(resultList);
	}

}
